package com.youran.restful.webprinter.util;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @see http://www.ibm.com/developerworks/cn/java/l-javaprint/
 * @author think
 *
 */
public class PrintWrapper {

	private static Logger logger = LoggerFactory.getLogger(PrintWrapper.class);
	
	private static PrintService selectedPrinter = null;

	private static Map<String, PrintService> printers = new HashMap<String, PrintService>();

	public void selectedPrintService(String printName) {
		if(printers.containsKey(printName)) {
			selectedPrinter = printers.get(printName);
			logger.info("设置默认打印机：{}", printName);
		} else {
			logger.warn("没有找到此打印机：{}", printName);
		}
	}

	/**
	 * 获取服务所在机器的所有打印服务名称
	 * 
	 * @return 如果本机没有打印服务，则返回空列表。
	 */
	public List<String> getPrinters() {
		List<String> printerNames = new LinkedList<String>();
		// 构建打印请求属性集
		PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
		// 设置打印格式，因为未确定文件类型，这里选择 AUTOSENSE
		DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
		// 查找所有的可用打印服务
		PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);

		for (PrintService print : printService) {
			printers.put(print.getName(), print);
			printerNames.add(print.getName());
		}
		logger.info("找到打印服务：{}", printerNames);
		return printerNames;
	}

	public void print(File sourceFile) {
		// 构建打印请求属性集
		PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
		// 设置打印格式，因为未确定文件类型，这里选择 AUTOSENSE
		DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
		// 查找所有的可用打印服务
		PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
		// 定位默认的打印服务
		PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
		// 显示打印对话框
		PrintService service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras);
		if (service != null) {
			try {
				DocPrintJob job = service.createPrintJob();// 创建打印作业
				FileInputStream fis = new FileInputStream(sourceFile);// 构造待打印的文件流
				DocAttributeSet das = new HashDocAttributeSet();
				Doc doc = new SimpleDoc(fis, flavor, das);// 建立打印文件格式
				job.print(doc, pras);// 进行文件的打印
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
